function debug(o){
	var debug = [];
	for(var p in o){
		debug.push(p+": "+o[p]);
	}
	return debug.join("\n");
}
String.prototype.encodeHTML = function(){
	return this.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
};
String.prototype.decodeHTML = function(){
	return this.replace(/&amp;/g,'&').replace(/&lt;/g,'<').replace(/&gt;/g,'>');
};
//以POST方式提交数据
function postData(url, dataObj, name){
	var _name = name || "_self";
	var tempForm = document.createElement("form");
	tempForm.id="tempForm1";
	tempForm.method="post";
	tempForm.action=url;
	tempForm.target=_name;
	
	if(dataObj){
		for(var p in dataObj){
			var hideInput = document.createElement("input");
			hideInput.type="hidden";
			hideInput.name= p;
			hideInput.value= dataObj[p];
			tempForm.appendChild(hideInput);
		}
	};
	document.body.appendChild(tempForm);
	tempForm.submit();
	document.body.removeChild(tempForm);
};
function getPageSize() 
{ 
	var body = document.documentElement || document;
	var pageDimensions = [0,0]; 

	var widths = [body.offsetWidth, body.scrollWidth];
	var heights = [body.offsetHeight, body.scrollHeight];
	for(var p in widths){
		pageDimensions[0] = Math.max(pageDimensions[0], widths[p]);
	}
	for(var p in heights){
		pageDimensions[1] = Math.max(pageDimensions[1], heights[p]);
	}
	return pageDimensions;
}
function showWait(btn){
	Mask.show(btn);
}
function hideWait(btn){
	Mask.hide(btn);
}
var Mask = {
	text: function(txt){
		$("#loading-text").html(txt);
		return this;
	},
	show: function(btn){
		var pageDims = getPageSize();
		$("#loading-mask").width(pageDims[0]+"px");
		$("#loading-mask").height(pageDims[1]+"px");
		$("#loading").show();
		$("#loading-mask").show();
		if(btn){
			$("#"+btn).attr("disabled", "disabled");
		}
		return this;
	},
	hide: function(btn){
		$("#loading-mask").hide();
		$("#loading").hide();
		if(btn){
			$("#"+btn).removeAttr("disabled");
		}
		return this;
	}
}

var Luban = {};
Luban.ajax = function(params){
	var backend = function(obj){
		if($.trim(obj).indexOf("lubanjson=")==0){
			//服务器出现超时或在别处登录等情况
			var json1=obj.substring(obj.indexOf("=")+1).replace(/\n|\r|\t/g,"");
			var sta=eval("["+json1+"]")[0];
			if(sta.satatuscode){
				//是期待中的数据格式
				if(sta.info!==""){
					alert(sta.info);
				}
				if(sta.forward!==""){
					top.location.href=sta.forward;
				}
				return false;
			}
		};
		return true;
	}
	var ajaxParams = jQuery.extend({}, params);
	ajaxParams.beforeSend = function(request){
		request.setRequestHeader("RequestType","request-in-script");
		request.setRequestHeader("x-requested-with","XMLHttpRequest");
	};
	var error = ajaxParams.error || jQuery.noop;
	ajaxParams.error = function(request,textStatus,errorThrown){
		if( backend(request.responseText) ){
			error(request, textStatus, errorThrown);			
		}
	}
	var success = ajaxParams.success || jQuery.noop;
	ajaxParams.success = function(data){
		if(typeof data == 'string'){
			if(backend(data)){
				success(data);
			}
		}else{
			success(data);
		}
	}
	jQuery.ajax(ajaxParams);
};

function checkAll(cbxName, el){
	var cbxName = cbxName || "checkedAll";
	var check = true;
	if(el){
		if(typeof el == 'string'){
			el = $("#"+el)[0];
		}
		check = el.checked;
	}
	var es = document.getElementsByName(cbxName);
	for(var i=0; i<es.length; i++){
		es[i].checked = check;
	}
}

function uncheckAll(cbxName){
	var cbxName = cbxName || "checkedAll";
	var es = document.getElementsByName(cbxName);
	for(var i=0; i<es.length; i++){
		es[i].checked = false;
	}
}

function checkReverse(cbxName){
	var cbxName = cbxName || "checkedAll";
	var es = document.getElementsByName(cbxName);
	for(var i=0; i<es.length; i++){
		es[i].checked = ! es[i].checked;
	}
}
function checkedIfAll(cbxName, cbxAllName){
	var es = document.getElementsByName(cbxName);
	var sa = document.getElementById(cbxAllName);
	for(var i=0; i<es.length; i++){
		if(! es[i].checked){
			sa.checked = false;return;
		}
	}
	sa.checked = true;
}
/*
 * 从源Select复制填充到目标Select
 */
function copyFillSelect(source, target, cache){
	if(!cache || target.options.length == 0){
		target.options.length = 0;
		var options = source.options;
		for(var i=0; i<options.length; i++){
			var option = options[i];
			target.options.add(new Option(option.text, option.value));
		}
	}
	target.selectedIndex = source.selectedIndex;
}
/**
 * 一个简单的ArrayList
 * 如果传入的是简单类型，则删除方法删除的元素可能非期望值，除非List中元素不重复
 */
function ArrayList(initCapt, increase){
	var initCapt = initCapt || 10;
	var increase = increase || 10;
	var array = [initCapt];
	var size = initCapt;
	var index = 0;
	var _add = function(e){
		if(index == array.length){
			var temp = array;
			array = [array.length + increase];
			for(var i=0;i<temp.length;i++){
				array[i] = temp[i];
			}
			index = array.length;
		}
		array[index++] = e;
	}
	this.add = function(){
		var len = arguments.length;
		if(len == 1){
			var e = arguments[0];
			if($.isArray(e)){
				for(var i=0;i<e.length;i++){
					_add(e[i]);
				}
			}else{
				_add(e);
			}
		}
		for(var i=0;i<arguments.length;i++){
			_add(arguments[i]);
		}
	};
	this.remove = function(e){
		var idx = 0;
		var found = false; //是否找到
		for(var i=0;i<array.length;i++){
			if(array[i] === e){
				idx = i;
				found = true;
				break;
			}
		}
		if(found){
			if(idx == array.length-1){
				array[idx] = null;
			}else{
				for(;idx<array.length-1;idx++){
					array[idx] = array[idx+1];
				}
			}
			index--;
			if((array.length - index) > increase){
				var temp = array;
				array = [array.length - increase];
				for(var i=0;i<temp.length;i++){
					array[i] = temp[i];
				}
				index = array.length;
			}
			return true;;
		}
		return false;
	};
	this.contains = function(e){
		for(var i=0;i<array.length;i++){
			if(array[i] === e){
				return true;
			}
		}
		return false;
	};
	this.indexOf = function(e){
		for(var i=0;i<array.length;i++){
			if(array[i] === e){
				return i;
			}
		}
		return -1;
	};
	this.get = function(idx){
		return array[idx];
	};
	this.size = function(){
		return index;
	};
}

$(document).ready(function(){
	jQuery.fn.extend({
		/**
		 * 使表格的列可调整宽度
		 * 参数类型：Object
		 * 可用选项：
		 * showResizeBar: boolean，默认：true 显示调整宽度条，如果表格列与列之间本身有边框，请设为false
		 * tableWidthFixed: boolean，默认：true 表格宽度是否固定，当为true时，整个表格的宽度会改变，否则会调整其他列的宽度
		 * excludeIndexes: array 不改变宽度的列索引，从0开始
		 */
		"setResizable": function(params){
			var _params = params || {};
			var showResizeBar = typeof _params.showResizeBar == 'boolean' ? _params.showResizeBar : true;
			var tableWidthFixed = typeof _params.tableWidthFixed == 'boolean' ? _params.tableWidthFixed : true;
			var excludeIndexes = _params.excludeIndexes || [];
			var ths = this;
			var len = ths.length;
			ths.each(function(i){
				var resizeBar = $(this).attr("resizeBar");
				if(resizeBar){return;}
				for(var idx in excludeIndexes){
					if(i == excludeIndexes[idx]){
						return;
					}
				}
				if(showResizeBar){//是否显示改变大小的竖条
					var br = this.style.borderRight;
					this.style.borderRight = "1px solid black";
					if(! br){br="0px none"};
					$(this).attr("resizeBar", br);
				}
				$(this).css({"margin":"0 0", "padding":"0 0"});
				var divWrapperStyle = "display:table;";
				var divLeftStyle = "display:table-cell;";
				var divRightStyle = "display:table-cell;";
				if($.browser.msie && ($.browser.version == '6.0' || $.browser.version == '7.0')){
					divWrapperStyle = '';
					divLeftStyle = "float:left;";
					divRightStyle = "float:right;";
				}
				var div = $("<div class='drag-wrapper' style='width:100%;height:100%;"+divWrapperStyle+"'></div>");
				var textWrapper = $("<div class='text-wrapper' style='"+divLeftStyle+"width:98%;height:100%;'></div>");
				$(this).wrapInner(textWrapper);
				$(this).wrapInner(div);
				$(this).find(".drag-wrapper").append("<div class='drag-el' style='"+divRightStyle+"height:100%;width:2px;'><span style='visibility:hidden;'>&nbsp;</span></div>");
			});
			$(".drag-el").css({"cursor": "w-resize"}).each(function(){
				$(this).bind("mousedown", function(event){
					var oleft = event.pageX;
					var thEl = $($(this).context.parentNode.parentNode);
					var thWidth = thEl.width();
					if(!tableWidthFixed){
						var tableEl = thEl.parents("table");
						var tableWidth = tableEl.width();
					}
					
					$(document).css({"cursor": "w-resize"}).bind("mousemove", function(event){
						var left = event.pageX;
						var move = left-oleft;
						thEl.width(thWidth + move);
						if(!tableWidthFixed){
							tableEl.width(tableWidth + move);
						}
					});
				})
				$(document).bind("mouseup",function(event){
					 $(this).css({"cursor": "default"}).unbind("mousemove");
				});
			});
			return this;
		},
		/**
		 * 移除表格列可调整宽度功能，即抵消setResizable的操作
		 */
		"removeResizable": function(){
			var ths = this;
			var len = ths.length;
			ths.each(function(i){
				if(i==(len-1))return;
				var rb = $(this).attr("resizeBar");
				if(rb){
					this.style.borderRight = rb;
					$(this).css({"border-right": rb}).removeAttr("resizeBar");
					var innerEl = $(".text-wrapper > *", this);
					var len = $(".text-wrapper > *", this).length;
					if(len == 0){
						innerEl = $(document.createTextNode($(".text-wrapper").html()));
					}
					innerEl.replaceAll($(".drag-wrapper", this));
				}
			});
			return this;
		},
		/**
		 * 使表头点击即可排序，表头TH或TD需要有sort属性
		 * 参数类型：Object
		 * 可用选项：
		 * ascChar: string，默认：▲ 升序时显示的字符
		 * descChar: string，默认：▼ 降序时显示的字符
		 * onclick: function 当点击表头时，回调的函数，
		 * 函数可用参数: 
		 * sort:String sort属性的值
		 * asc: boolean 是否为升序
		 * obj: Object 排序对象
		 */
		"setSortable": function(params){
			var _params = params || {};
			var ascChar = _params.ascChar || "<span class=\"sortasc\">&nbsp;</span>";
			var descChar = _params.descChar || "<span class=\"sortdesc\">&nbsp;</span>";
			var onclick = _params.onclick || jQuery.noop;
			var transChar = function(str, o, n){
				return str.replace(o, n)
			};
			var SortManager = {};
			this.each(function(){
				var sort = $(this).attr("sort");
				if(sort){
					var text = $(this).text();
					//设置初始排序样式
					if(_params[sort] == sort){
						$(this).html(text+(_params.asc ? ascChar : descChar));
					}
					var sortId = transChar(sort, ".", "-");
					var span = $("<span></span>");
					span.attr("id", "sort-wrapper-"+sortId);
					span.attr("sort", sort);
					
					$(this).wrapInner(span);
					SortManager[sort] = {
						source: $("#sort-wrapper-"+sortId),
						text: text,
						asc : true
					};
					$("#sort-wrapper-"+sortId).css({"cursor": "pointer"}).bind("click", function(){
						var _sort = $(this).attr("sort");
						//清理其他排序样式
						for(var p in SortManager){
							var _obj = SortManager[p];
							_obj.source.html(_obj.text);
						}
						var _text = SortManager[_sort].text;
						var _asc = SortManager[_sort].asc;
						if(_asc){
							$(this).html(_text + ascChar);
							SortManager[_sort].asc = false;
						}else{
							$(this).html(_text + descChar);
							SortManager[_sort].asc = true;
						}
						//执行分页查询
						onclick(_sort, _asc, SortManager[_sort]);
					});
				}
			});
			return this;
		},
		"showLoadingIcon":function(){
			this.html($("#loading-img").html());
		}
	});
});